package JdbcTemplate;

import Druid.Druid1;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {
    static Properties properties=null;
    static DataSource dataSource=null;
    static {
        //加载配置文件的方法
        properties=new Properties();
        //通过字节码获取类加载器
        InputStream resourceAsStream = Druid1.class.getClassLoader().getResourceAsStream("druid.properties");//将配置文件转化为流
//读去配置文件
        try {
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //创建获取连接的方法
    public static Connection getconnection() throws Exception {
        //获取连接
        Connection connection = dataSource.getConnection();
        return connection;

    }
    //创建获取连接池的方法
    public static DataSource getDataSource(){
        return dataSource;
    }
    //归还连接
    public static void close(Connection connection, ResultSet set,Statement statement){
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (set!=null){
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
